import {getLoader, logger} from '@react-native-community/cli-tools';
import execa from 'execa';
import fs from 'fs';
import path from 'path';

export const checkGitInstallation = async (): Promise<boolean> => {
  try {
    await execa('git', ['--version'], {stdio: 'ignore'});
    return true;
  } catch {
    return false;
  }
};

export const checkIfFolderIsGitRepo = async (
  folder: string,
): Promise<boolean> => {
  try {
    await execa('git', ['rev-parse', '--is-inside-work-tree'], {
      stdio: 'ignore',
      cwd: folder,
    });
    return true;
  } catch {
    return false;
  }
};

export const createGitRepository = async (folder: string) => {
  const loader = getLoader();

  loader.start('Initializing Git repository');

  let version;

  try {
    version = JSON.parse(
      fs.readFileSync(
        path.join('node_modules/react-native/package.json'),
        'utf8',
      ),
    ).version;
  } catch {}

  try {
    await execa('git', ['init'], {cwd: folder});
    await execa('git', ['branch', '-M', 'main'], {cwd: folder});
    await execa('git', ['add', '.'], {cwd: folder});
    await execa(
      'git',
      [
        'commit',
        '-m',
        `Initial commit\n\n${
          version ? 'Generated by react-native@' + version : ''
        }`,
      ],
      {
        cwd: folder,
      },
    );
    loader.succeed();
  } catch (e) {
    loader.stop();
    logger.debug(
      'Could not create an empty Git repository, error: ',
      e as string,
    );
  }
};
